<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:th="http://www.thymeleaf.org"
      xmlns:sec="http://www.thymeleaf.org/thymeleaf-extras-springsecurity3" xmlns:head="http://www.w3.org/1999/html">
<link rel="stylesheet" type="text/css" th:href="@{/plugin/layui/css/font/iconfont.css}" media="all"/>
<link rel="stylesheet" type="text/css" th:href="@{/plugin/layui/js/layui/css/layui.css}"  media="all"/>
<link rel="stylesheet" type="text/css" th:href="@{/plugin/bootstrap/bootstrap/css/bootstrap.min.css}"/>
<link rel="stylesheet" type="text/css" th:href="@{/plugin/bootstrap-table/bootstrap-table.css}"/>
<link rel="stylesheet" type="text/css" th:href="@{/css/table.css}"  media="all"/>
<link rel="stylesheet" type="text/css" th:href="@{/css/scrollbar.css}"  media="all"/>
<link rel="stylesheet" type="text/css" th:href="@{/plugin/bootstrap/bootstrap/css/bootstrap.min.css}"/>
<link rel="stylesheet" type="text/css" th:href="@{/plugin/layui/js/select2/css/select2.css}" media="all"/>
<link href="zxsdwms/plugin/font-awesome/css/font-awesome.css/font-awesome.min.css" rel="stylesheet">
<link rel="stylesheet" type="text/css" th:href="@{/plugin/ztree/metroStyle/metroStyle.css}" media="all"/>

<body >
<form action="" class="layui-form layui-form-pane" id="addForm">
    <input type="hidden" class="layui-input" th:value="${id}" id="inputID" name="id">
    <!--<div>-->
            <!--&lt;!&ndash;库位树结构&ndash;&gt;-->
            <!--<input type="hidden" id="librarypositionIds" name="librarypositionIds">-->
            <!--<ul id="menuTree" class="ztree" data-required ></ul>-->
    <!--</div>-->
    <div class="row">
        <div class="col-xs-6">
            <div style="padding: 15px">
                <form class="form-horizontal" role="form" id="details_form">
                    <div class="form-group" style="display: none">
                        <div class="col-sm-8">

                        </div>
                    </div>
                    <div id="tree"></div>
                </form>
            </div>
        </div>
    </div>
    <a class="layui-btn" id="editSave" lay-submit="" lay-filter="demo1">保存</a>
</form>
</body>

<div th:include="public/public_js::public_js"></div>
<script th:src="@{/plugin/beyond/assets/js/fuelux/wizard/wizard-custom-yjs.js}"></script>
<script>
    var id = $('#inputID').val();
    var idsarr = [];
    var Sbarr = [];   // 库区ids节点
    var childrenarr = [];  // 库位ｉｄｓ节点
    var cancelarr = [];   // 反选ids 节点
    var recallarr = [];
    var datas;
    $(function () {
        var tree = function () {
            console.log("开始啦。。。");

            $.ajax({
                type: "get",
                url: "/zxsdwms/wmsOwner/searchKw/"+ id,
                dataType: "JSON",
                async: false,
                success: function (data) {
                    console.log('dadddd',data);
                    datas = data;
                    //将数据添加到省份这个下拉框里面

                },
                error: function () { alert("Error"); }
            });

            var treedata = treeDataFormat(datas);
            console.log(treedata);
//                    var trees = {};
//                    var treess = [];
//                    trees.text = "销售系统";
//                    trees.nodes = treedata;
//                    treess.push(trees);
//                    console.log(trees);

//                    var resultMap = eval(data);
//                    var map={};
//                    map.mc="销售系统";
//                    map.children=resultMap;
//                    map.nodes=resultMap;
//                    var maps=[];
//                    maps.push(map);
//                    maps.forEach(function (e) {//遍历集合
//                        serializ(e);//把集合的每一项放到序列化方法中序列化
//                    });
            //选中父节点时，选中所有子节点

            // 选中
            function getChildNodeIdArr(node) {
                console.log('node',node);
                var ts = [], ids = [];
                console.log('ts',ts);
                if (node.nodes) {
                    console.log('if');
                    for (x in node.nodes) {
                        ts.push(node.nodes[x].nodeId);
                        ids.push(node.nodes[x].id);
//                        if (node.nodes[x].nodes) {
//                            var getNodeDieDai = getChildNodeIdArr(node.nodes[x]);
//                            for (j in getNodeDieDai) {
//                                ts.push(getNodeDieDai[j]);
//                            }
//                        }
                    }
//                                console.log('fufu',ids);
                } else {
                    ts.push(node.nodeId);
//                            console.log('else',ts);
//                            console.log('else,node',node);
                }

                return ts;
            }
            // 选中所有子节点时，选中父节点 取消子节点时取消父节点
            function setParentNodeCheck(node) {
                var parentNode = $("#tree").treeview("getNode", node.parentId);
                if (parentNode.nodes) {
                    var checkedCount = 0;
                    for (x in parentNode.nodes) {
                        if (parentNode.nodes[x].state.checked) {
                            checkedCount ++;
                        } else {
                            break;
                        }
                    }
                    if (checkedCount == parentNode.nodes.length) {  //如果子节点全部被选 父全选
                        $("#tree").treeview("checkNode", parentNode.nodeId);
                        setParentNodeCheck(parentNode);
                    }else {   //如果子节点未全部被选 父未全选
                        $('#tree').treeview('uncheckNode', parentNode.nodeId);
                        setParentNodeCheck(parentNode);
                    }
                }
            }

            // 取消父节点时 取消所有子节点
            function setChildNodeUncheck(node) {
                if (node.nodes) {
                    var ts = [], ids = [];    //当前节点子集中未被选中的集合
                    for (x in node.nodes) {
                        if (!node.nodes[x].state.checked) {
                            ts.push(node.nodes[x].nodeId);
                            ids.push(node.nodes[x].id);//将所有子节点push到ids中
                        } else if (node.nodes[x].nodes) {
//                                    alert('else,if');
                            var getNodeDieDai = node.nodes[x];
                            console.log(getNodeDieDai);
                            for (j in getNodeDieDai) {
                                if (!getNodeDieDai.state.checked) {
                                    ts.push(getNodeDieDai[j]);
                                }
                            }
                        }
                    }
                }
                return ts;
            }
            $('#tree').treeview(
                {//树结构初始化，具体参数查阅bootstrap-treeview中文api
                    color: "#428bca",
                    levels: 2, // 初始收缩
//                        selectedBackColor: false,
                    showBorder: true,
                    showCheckbox: true,    //这里之所以写1，是因为我引得js源码里定义1为true
                    multiSelect: 0, //这里之所以写1，是因为我引得js源码里定义1为true    //多选
                    data: treedata,
                    hierarchicalCheck:true,
                    selectable: true,
                    highlightSelected: true,
                    onNodeChecked: function(event, node) { //选中节点
//                        alert('添加1');
                        if ('nodes' in node) {
                            Sbarr.push(node.id);       // 判断nodes是否有子节点。如果有就将跟节点的ID,push,Sbarr
                            childrenarr = [];
                            for (var x=0;x < node.nodes.length;x++) {
                                   childrenarr.push(node.nodes[x].id);
                                for (var j = 0; j < cancelarr.length; j++) {
                                    if (cancelarr[j] == node.nodes[x].id) {
                                        cancelarr.splice(j,1);
                                    }
                                }
                            }
                            // 传库区id,删除库位childrenarr
//                            for (var x=0;x < node.nodes.length;x++) {
//                                for (var y=0;y<childrenarr.length;y++){
//                                    if(node.nodes[x].id == childrenarr[y]) {
//                                        childrenarr.splice(y,1);
//                                    }
//                                }
//                            }
                        } else {
                            for (var i = 0; i < cancelarr.length; i++) {
                                if (cancelarr[i] == node.id) {
//                                alert(i);
                                    cancelarr.splice(i,1);
                                }
                            }
                            childrenarr.push(node.id);
                        }
                        var selectNodes = getChildNodeIdArr(node); //获取所有子节点
                        console.log('selectNodes',selectNodes);
                        if (selectNodes) { //子节点不为空，则选中所有子节点
                            $('#tree').treeview('checkNode', [selectNodes, { silent: true }]);
                        }
//                            var parentNode = $("#tree").treeview("getNode", node.parentId);
                        setParentNodeCheck(node);
                        $('#tree').prop('checked',true);
                    },
                    onNodeUnchecked: function(event, node) {
                        //取消选中节点
                        // 判断未选中数组里是否有当前选中的节点
                        if ('nodes' in node) {
                            //
                            for (var i = 0; i < Sbarr.length; i++) {
                                if (Sbarr[i] == node.id) {
                                    Sbarr.splice(i,1);
                                }
                            }
                            // 删除取消，子节点反选
                            for (var ii = 0; ii < cancelarr.length; ii++) {
                                if (cancelarr[ii] == node.id) {
                                    cancelarr.splice(ii,1);
                                }
                            }
                        } else {
                            var tmp = true;
                            for (var i = 0; i < childrenarr.length; i++) {
                                if (childrenarr[i] == node.id) {
                                    childrenarr.splice(i,1);
//                                    tmp = false;
                                }
                            }
                            var parentNode = $("#tree").treeview("getNode", node.parentId); // 获取父节点数据

                            // 删除取消，子节点反选
                            for (var ii = 0; ii < cancelarr.length; ii++) {
                                if (cancelarr[ii] == node.id) {
                                    cancelarr.splice(ii,1);
                                }
                            }
                            console.log('tmp');
                            if (tmp) {
                                cancelarr.push(node.id);
                            }
                        }

                        var selectNodes = setChildNodeUncheck(node); //获取未被选中的子节点
                        var childNodes  = getChildNodeIdArr(node); //获取未被选中的子节点
                        if (selectNodes && selectNodes.length===0) { //有子节点且未被选中的子节点数目为0，则取消选中所有子节点
                            console.log("反选");
                            $('#tree').treeview('uncheckNode', [childNodes, { silent: true }]);
                        }
                        // 取消节点 父节点取消
//                            var parentNode = $("#tree").treeview("getNode", node.parentId);  //获取父节点
//                            var selectNodes = getChildNodeIdArr(node);
                        setParentNodeCheck(node);
                    },
                });
        }
        var init =function () {
            tree();
        };
        init()//初始化
    });
    function treeDataFormat(data) {
        var arr = [];
        for (var i = 0; i < data.length; i++) {
            var  Is = {};
            Is.text = data[i].label;
            Is.id = data[i].key;
            Is.state= {
                disabled:false,
                expanded:false,
                selected:false
            }
            if (data[i].checked === 'isChecked') {
                Is.state.checked = true;
            } else {
                Is.state.checked = false;
            }
            if (data[i].children.length > 0) {
                Is.nodes = treeDataFormat(data[i].children);
            }
            arr.push(Is);
        }
        return arr;
    }
    $('#save').click(function () {
//        $('#tablesec').css('display', 'block');
        BiaoTou();
    });
    function BiaoTou () {
        var data = [];
        var treeids =  $('#tree').treeview('getChecked');
        if (treeids.length > 0) {
            treeids.forEach(item => {
//                                console.log('item', item.id);
                idsarr.push(item.id);
            });
        } else {
            idsarr = []
        }
        console.log('idsarr', idsarr);
        $.ajax({
            //方法类型
            type: "POST",
            //scriptCharset: "utf-8",
            //几个参数需要注意一下
            async: false,
            url: "/zxsdwms/statistics/goodsTypeStatisticsTitle" ,
            data: JSON.stringify({
                "channeIds": idsarr,
                "page":1,
                "rows":10
            }),
            contentType:"application/json",
            success: function (returnValue){
                data = returnValue
//                    console.log('打印data', JSON.stringify(data));
//                    ajaxdata.push({"field": '',
//                        "checkbox": true,
//                    });
                // 异步获取要动态生成的列
            },
        });
    }
    // 保存
    $('#editSave').click(function () {
        console.log('库区',Sbarr,);
        console.log('库位',childrenarr);
        console.log('反选',cancelarr);
        console.log(123456, datas);
        var kuquarr = [];    // 初始数据
        var savekuquadd = [];
        var savekuqudel = [];
        var savekuweiadd = [];
        var savekuweidel = [];
        datas.forEach(function (item) {
            if (item.checked !== '') {
                kuquarr.push({key: item.key, val:item.nodes});
            }
        });

        console.log(666666666, kuquarr);
        for (var it = 0; it < Sbarr.length; it++) {
            var type;
            type = kuquarr.some(function (item) {
                console.log(11111112222222, Sbarr[it], item.key);
                return Sbarr[it] !== item.key;
            });
            if (type) {
                savekuquadd.push(Sbarr[it]);
            }
        }


        // 对比 库位
        for (var i = 0; i<savekuquadd.length;i++) {
            for (var z=0;z<kuquarr.length;z++) {
                if (savekuquadd[i] == kuquarr[z].key) {
                    console.log(22222222, kuquarr[z].val);
                    /*for(var ii = 0;ii < kuquarr[z].val.length; ii++) {
                        childrenarr.splice(arrlen(childrenarr, kuquarr[z].val[ii]), 1);
                    }*/
                }
                break;
            }
        }
        console.log(11111111111, childrenarr);


//        $.ajax({
//            type: "post",
//            url: "/zxsdwms/wmsOwner/searchKw/"+ id,
//            dataType: "JSON",
//            async: false,
//            success: function (data) {
//                console.log('dadddd',data);
//                datas = data;
//                //将数据添加到省份这个下拉框里面
//
//            },
//            error: function () { alert("Error"); }
//        })

    })

    function arrlen(data, val){
        var len;
        data.forEach(function(item, index) {
            if (item === val) {
                len = index;
            }
        });
        return len;
    }

</script>
</html>